package cn.pomit.springbootwork.lock.redis.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cn.pomit.springbootwork.lock.redis.dao.TUserGoodDao;
import cn.pomit.springbootwork.lock.redis.domain.TGoodInfo;
import cn.pomit.springbootwork.lock.redis.domain.TUserGood;
import cn.pomit.springbootwork.lock.redis.dto.ResultModel;
import cn.pomit.springbootwork.lock.redis.inter.ConsumeService;
import cn.pomit.springbootwork.lock.redis.inter.GoodsInfoService;

@Service("UserConsumeService")
public class UserConsumeService implements ConsumeService {
	protected Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	GoodsInfoService goodsInfoService;
	@Autowired
	TUserGoodDao tUserGoodDao;

	@Value("${server.port}")
	private Integer serverId;

	public ResultModel goodList(Integer page, Integer size) {
		List<TGoodInfo> pageList = goodsInfoService.getGoodsList(page, size);
		return ResultModel.ok(pageList);
	}

	public ResultModel goodDetail(Integer goodId) {
		return ResultModel.ok(goodsInfoService.getGoodsInfo(goodId));
	}

	public ResultModel consume(Integer goodId, Integer num, String userName) {
		log.info("开始消费：userName：{};goodId:{},num:{}", userName, goodId, num);

		TGoodInfo tGoodInfo = goodsInfoService.getGoodsInfo(goodId);

		log.info("消费前：goodId:{}剩余:{}", goodId, tGoodInfo.getGoodNum());

		Integer ret = goodsInfoService.consume(goodId, num, serverId);

		log.info("消费结果：ret：{};", ret);
		if (ret > 0) {
			log.info("保存用户消费信息");
			TUserGood tUserGood = new TUserGood();
			tUserGood.setConsumeNum(num);
			tUserGood.setGoodId(goodId);
			tUserGood.setUserName(userName);
			tUserGoodDao.save(tUserGood);
			return ResultModel.ok();
		}
		return ResultModel.error("消费失败！");
	}

}
